package com.ruoyi.common.db;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.ruoyi.common.cache.AbstractCache;
import net.oschina.j2cache.CacheChannel;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <pre>
 *
 * </pre>
 *
 * @author zhangli
 * @since 2023/10/19
 */
public abstract class CacheService<KeyType extends Serializable, Po extends ID<KeyType>> extends BaseService<KeyType, Po> {

    @Autowired
    private AbstractCache<KeyType,Po> cache;

    @Override
    public Po getById(KeyType id) {
        return cache.get(id, stringKey -> super.getById(id));
    }

    @Override
    public boolean save(Po po) {
        boolean save = super.save(po);
        cache.save(po);
        return save;
    }

    @Override
    public boolean save(List<Po> pos) {
        boolean save = super.save(pos);
        cache.save(pos.stream()
                .collect(Collectors.toMap(ID::getId, p -> p))
        );

        return save;
    }

    @Override
    public boolean removeById(KeyType id) {
        boolean result = super.removeById(id);
        cache.remove(id);
        return result;
    }
}
